#include "AuthenticationCreate.h"
#include "ui_AuthenticationCreate.h"
#include "Tools/UiUpdateMediator.h"
#include "Tools/MyUrl.h"

#include <QNetworkAccessManager>
#include <QJsonObject>
#include <QJsonDocument>
#include <QNetworkAccessManager>
#include <QUrl>
#include <QNetworkRequest>
#include <QNetworkReply>

AuthenticationCreate::AuthenticationCreate(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::AuthenticationCreate)
{
    ui->setupUi(this);

    this->ui->widget_mysql_message->setVisible(false);
    this->ui->radioButton_localDataBase->setChecked(true);
}

AuthenticationCreate::~AuthenticationCreate()
{
    delete ui;
}

void AuthenticationCreate::on_radioButton_MysqlDataBase_toggled(bool checked)
{
    if(checked == true)
    {
        this->ui->widget_mysql_message->setVisible(true);
    }
    else
    {
        this->ui->widget_mysql_message->setVisible(false);
    }
}

void AuthenticationCreate::on_pushButton_save_clicked()
{
    QString device_name = this->ui->lineEdit_deviceName->text();
    QString product_name = this->ui->lineEdit_productName->text();
    QString creator = this->ui->lineEdit_creator->text();

    if(this->ui->lineEdit_deviceName->text().isEmpty() ||
       this->ui->lineEdit_productName->text().isEmpty() ||
       this->ui->lineEdit_creator->text().isEmpty())
    {
        qDebug() << "输入完整信息" << __LINE__ << __FILE_NAME__;
        return;
    }

    QNetworkAccessManager* manager = new QNetworkAccessManager();
    connect(manager, &QNetworkAccessManager::finished, this, [=](QNetworkReply* reply){
        int stateCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
        if(stateCode == 200)
        {
            qDebug() << "认证添加成功" << __LINE__ << __FILE_NAME__;
            emit UiUpdateMediator::getInstance()->updateDevice();
            emit UiUpdateMediator::getInstance()->updateAuthentication();
        }
    });

    QJsonObject jsonData;
    jsonData["device_name"] = device_name;
    jsonData["product_name"] = product_name;
    jsonData["creator"] = creator;

    QJsonDocument doc(jsonData);
    QNetworkRequest* request = new QNetworkRequest(QUrl(MyUrl::authCreate));
    request->setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
    manager->post(*request, doc.toJson(QJsonDocument::Compact));
}

